package org.csu.mypetstore.service;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.persistence.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AccountService {
    @Autowired
    private AccountMapper accountMapper;

    public Account getAccount(String username) {
        return accountMapper.getAccountByUsername(username);
    }

    public Account getAccount(String username, String password) {
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);
        return accountMapper.getAccountByUsernameAndPassword(account);
    }

    public void insertAccount(Account account) {
        accountMapper.insertAccount(account);
        accountMapper.insertProfile(account);
        accountMapper.insertSignon(account);
    }

    public void updateAccount(Account account) {
        accountMapper.updateAccount(account);
        accountMapper.updateProfile(account);

        if (account.getPassword() != null && account.getPassword().length() > 0) {
            accountMapper.updateSignon(account);
        }
    }

    public boolean isAccountExist(String username){
        boolean isExist = true;
        if (accountMapper.getAccountByUsername(username) == null){
            isExist = false;
        }
        return isExist;
    }

    public boolean isAdministrator(String username){
        boolean isAd = true;
        if(accountMapper.getAdministrator(username) == null){
            isAd = false;
        }

        return isAd;
    }

    public List<Account> getAccountList(){
        List<Account> accountList = new ArrayList<>();
        accountList = accountMapper.getAccountListByUsername();

        return accountList;
    }

    public void updatePassword(String username, String password){
        Account account = new Account();
        account.setUsername(username);
        account.setPassword(password);

        accountMapper.updateAccountPassword(account);
    }
}
